<template>
    <!--  定时任务-->
    <div class="user-manage">
        <div class="user-main">
            <div class="search-container">
                <el-form
                    ref="ruleFormRef"
                    :model="queryParams.entity"
                    label-width="80"
                    inline
                >
                    <el-form-item label="任务名称" prop="scheduleName">
                        <el-input
                            v-model="queryParams.entity.scheduleName"
                            maxlength="60"
                            placeholder="请输入任务名关键字"
                            clearable
                            @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            type="primary"
                            icon="Search"
                            @click="handleQuery"
                        >
                            搜索
                        </el-button>
                        <el-button icon="Refresh" @click="handleResetQuery">
                            重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
            <el-card shadow="never" class="table-container">
                <template #header>
                    <div
                        style="
                            display: flex;
                            justify-content: flex-start;
                            width: 100%;
                        "
                    >
                        <el-button
                            type="success"
                            icon="Plus"
                            @click="handleOpenAuthorDrawer"
                        >
                            新增
                        </el-button>
                        <el-button
                            type="primary"
                            icon="setting"
                            @click="executeTaskDrawer"
                        >
                            批量执行
                        </el-button>
                    </div>
                </template>
                <el-table
                    v-loading="tableLoading"
                    :data="tableData"
                    highlight-current-row
                    border
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column type="selection" width="55" />
                    <el-table-column
                        v-for="(item, index) in columnData"
                        :key="index"
                        :prop="item.prop"
                        :label="item.label"
                        min-width="120"
                        :width="item.width || ''"
                        :fixed="item.fixed || false"
                        show-overflow-tooltip
                        :resizable="false"
                        align="center"
                    >
                        <template #default="{ row }">
                            <span v-if="item.prop === 'state'">
                                <el-tag
                                    v-if="row[item.prop] === '1'"
                                    type="success"
                                    effect="dark"
                                >
                                    启用
                                </el-tag>
                                <el-tag
                                    v-if="row[item.prop] === '0'"
                                    type="danger"
                                    effect="dark"
                                >
                                    禁用
                                </el-tag>
                            </span>

                            <span
                                v-else-if="item.prop === 'scheduleCode'"
                                @click="gotoLog(row[item.prop])"
                                style="color: #3399cc; cursor: pointer"
                                >{{ row[item.prop] }}</span
                            >
                            <span v-else>{{ row[item.prop] }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="150">
                        <template #default="scope">
                            <el-button
                                type="primary"
                                icon="edit"
                                link
                                @click="handleOpenUserDrawer(scope.row)"
                            >
                                编辑
                            </el-button>
                            <el-button
                                type="danger"
                                icon="delete"
                                link
                                @click="deleteTaskDrawer(scope.row)"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <Pagination
                    v-if="total > 0"
                    v-model:total="total"
                    v-model:page="queryParams.pageNo"
                    v-model:limit="queryParams.pageSize"
                    @pagination="handleQuery"
                />
            </el-card>
        </div>
    </div>
    <!-- 编辑CRM用户 -->
    <!--  <CrmEditModel-->
    <!--    :userParams="userParams"-->
    <!--    @close="handleCloseUserDrawer"-->
    <!--  ></CrmEditModel>-->
    <!-- 新增CRM用户 -->
    <AddTimeList :userParams="authorParams" @close="handleCloseAuthorDrawer">
    </AddTimeList>
    <!--  编辑-->
    <EditTime
        :userParams="userParams"
        @close="handleCloseUserDrawer"
    ></EditTime>
</template>
<script setup>
defineOptions({ name: 'ScheduledTask' })
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination.vue'
// import CrmEditModel from './crrmeditmodel.vue'
import AddTimeList from './addtimelist.vue'
import EditTime from './edittime.vue'
import { deleteTask, postExecuteTask } from './api'
import { useRouter } from 'vue-router'

const router = useRouter()

// 引入全局化储存
import { userStore } from '../../store/index'

const store = userStore()

// 授权
import { getDeptTree } from '@views/deptManage/api/deptManage'
import { postTaskList } from './api'

const userParams = reactive({ visible: false })
const authorParams = reactive({ visible: false })

// 打开弹窗
const handleOpenUserDrawer = (row) => {
    userParams.row = row
    userParams.visible = true
}
// 关闭弹窗
const handleCloseUserDrawer = (type) => {
    userParams.visible = false
    if (type) handleQuery()
}

// 打开授权弹框
const handleOpenAuthorDrawer = (row) => {
    authorParams.row = row
    authorParams.visible = true
}
// 关闭授权弹窗
const handleCloseAuthorDrawer = (type) => {
    authorParams.visible = false
    if (type) handleQuery()
}
const treeLoading = ref(false)
const tableLoading = ref(false)
const deptRootOptions = ref([])
const queryParams = reactive({
    entity: { scheduleName: '' },
    pageNo: 1,
    pageSize: 15
})
const total = ref(0)
const columnData = ref([
    {
        label: '任务编码',
        prop: 'scheduleCode'
    },
    {
        label: '任务名称',
        prop: 'scheduleName',
        fixed: 'left'
    },
    {
        label: '执行表达式',
        prop: 'cron'
    },
    {
        label: '启用状态',
        prop: 'state'
    },
    {
        label: '有效开始时间',
        prop: 'validStartDate'
    },
    {
        label: '有效结束时间',
        prop: 'validEndDate'
    },
    {
        label: '创建人',
        prop: 'createName'
    },
    {
        label: '创建时间',
        prop: 'createDate'
    },
    {
        label: '更新人',
        prop: 'lastUpdateName'
    },
    {
        label: '更新时间',
        prop: 'lastUpdateDate'
    }
])
const tableData = ref([])
const ruleFormRef = ref(null)

// 获取数据
const handleQuery = async () => {
    tableLoading.value = true
    const res = await postTaskList(queryParams)
    tableLoading.value = false
    if (res?.code === 200) {
        tableData.value = res.data.records || []
        total.value = res.total || 0
    }
}

// 重置表单
const handleResetQuery = () => {
    ruleFormRef.value.resetFields()
    queryParams.pageNo = 1
    handleQuery()
}
// 删除
const deleteTaskDrawer = (row) => {
    ElMessageBox.confirm('确认删除定时任务？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            try {
                const res = await deleteTask(row.id)
                if (res.code === 200) {
                    ElMessage.success('删除成功')
                    handleQuery()
                }
            } catch (error) {
                console.error('Request error:', error)
            }
        })
        .catch(() => {})
}
const execuList = ref([])
const handleSelectionChange = (val) => {
    const idlist = val.map((item) => item.id)
    execuList.value = idlist
}
// 执行
const executeTaskDrawer = () => {
    ElMessageBox.confirm('确认执行定时任务？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            let obj = execuList.value
            try {
                const res = await postExecuteTask(obj)
                if (res.code === 200) {
                    ElMessage.success('执行成功')
                    handleQuery()
                }
            } catch (error) {
                console.error('Request error:', error)
            }
        })
        .catch(() => {})
}
// 跳转日志页面
const gotoLog = (code) => {
    store.setCode(code)
    router.push({ path: '/task/task-log' })
}
// 初始化
onMounted(() => {
    handleQuery()
})
</script>
<style lang="scss" scoped>
.user-manage {
    display: flex;
    height: 100%;

    .tree-main {
        width: 200px;
        background: #fff;
        padding: 10px;
    }

    .user-main {
        flex: 1;
        width: 0;
        margin-left: 10px;
    }
}
</style>
